package hikari.script.propertyeditors;

import com.gooddies.texteditors.DefaultIntegerTextField;
import hikari.gui.guicomponents.hLabel;
import hikari.persistence.file.FileSection;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.IOException;

/**
 * @author sad
 */
public class IntegerPropertyEditor extends IPropertyEditor<Integer> {

    private hLabel label;
    private DefaultIntegerTextField textField;

    public IntegerPropertyEditor(String caption, int value) {
        setLayout(new BorderLayout());
        label = new hLabel(caption);
        add(label, BorderLayout.WEST);
        textField = new DefaultIntegerTextField();
        textField.setPreferredSize(new Dimension(100, 20));
        add(textField);
    }

    public void setCaption(String caption) {
        label.setText(caption);
        validate();
        repaint();
    }

    public String getCaption() {
        return label.getText();
    }

    @Override
    public void setValue(Integer value) {
        textField.setValue(value);
    }

    @Override
    public Integer getValue() {
        return textField.getValue();
    }

    @Override
    public String sectionName() {
        return "int";
    }

    @Override
    public void save(FileSection section) throws IOException {
        FileSection valSection = section.createNewSection(sectionName());
        valSection.writeInt("val", getValue());
        valSection.writeString("name", getCaption());
        valSection.close();
    }

    @Override
    public void load(FileSection section) throws IOException {
        Integer value = section.readInt(section.getChunk("val"));
        setValue(value);
        setCaption(section.readString(section.getChunk("name")));
    }
}